package com.snailct.bpp.service.core.handle;

import com.snailct.bpp.commons.exception.ErrorCode;
import com.snailct.bpp.commons.utils.DBManager;
import com.snailct.bpp.service.core.CoreException;
import com.snailct.bpp.service.core.definition.DefaultServiceDefinition;
import com.snailct.bpp.service.core.definition.ServiceDefinition;
import com.snailct.bpp.service.core.definition.ServiceMeta;
import com.snailct.bpp.service.core.definition.ServiceType;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 服务仓库
 */
public class ServiceRepository {
    private enum ServiceReposError{
        @ErrorCode(comment = "The args is illegal!")
        DEFINITION_ERROR
    }
    public ServiceDefinition getServiceDefinition(ServiceDefinition serviceDefinition){
        DefaultServiceDefinition result = (DefaultServiceDefinition)serviceDefinition;
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            conn = DBManager.getConnection();
            st = conn.createStatement();
            rs = st.executeQuery("select * from S_SERVICE_DEFINITION where service_id='"+result.getServiceId()+"'");
            while(rs.next()){
                result.setServiceAddr(rs.getString("WS_ADDR"));
                result.setMethodName(rs.getString("METHOD_NAME"));
                result.setServiceType(ServiceType.getServiceType(rs.getString("service_type")));
                result.setComponent(rs.getString("COMPONENT"));
            }

            rs = st.executeQuery("select * from s_service_meta s where s.service_id='"+result.getServiceId()+"' order by param_num DESC ");
            ServiceMeta serviceMeta = null;
            while (rs.next()){
                serviceMeta = new ServiceMeta();
                serviceMeta.setParamType(rs.getString("param_type"));
                serviceMeta.setParamNo(rs.getString("param_num"));
                result.addServiceMeta(serviceMeta);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(st!=null){
                try {
                    st.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }
        if(!result.validate()){
            throw new CoreException(ServiceReposError.DEFINITION_ERROR);
        }
        return result;
    }
}
